//
//  UIView+LoadImage.m
//  EnTT
//
//  Created by 罗亮富 on 2016/11/14.
//
//

#import "UIView+LoadImage.h"

static NSURLSession *_gImageSession;

@implementation UIView (LoadImage)

+(NSURLSession *)loadSession
{
    if(!_gImageSession)
    {
        NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
        // sessionConfig.timeoutIntervalForRequest = 120.0;
        
        //cache
        NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:1024*1024*20 diskCapacity:1024*1024*500 diskPath:@"EnttImages"];
        sessionConfig.URLCache = cache;
        sessionConfig.requestCachePolicy = NSURLRequestReturnCacheDataElseLoad;
        
        
        _gImageSession = [NSURLSession sessionWithConfiguration:sessionConfig];
    }
    
    return _gImageSession;
}

-(UIActivityIndicatorView *)indicatorView
{
    UIActivityIndicatorView *v = [self viewWithTag:-70028765];
    if(!v)
    {
        v = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        v.center =  CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
        v.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
        v.tag = -70028765;
        [self addSubview:v];
        v.hidesWhenStopped = YES;
    }
    
    return v;
}

-(NSURLSessionDataTask *)currentTask
{
    return nil;
}

-(void)setCurrentTask:(NSURLSessionDataTask *)task
{
    
}

-(void)setImageURLStr:(NSString *)urlStr placeHolderImage:(UIImage *)image loadingIndicate:(BOOL)indicate
{
    if(!urlStr)
    {
        [self setDisplayImage:image];
    }
    else
    {
        NSURL *url = [NSURL URLWithString:urlStr];
        [self setImageURL:url placeHolderImage:image];
    }
}

-(void)setImageURLStr:(NSString *)urlStr placeHolderImage:(UIImage *)image
{
    [self setImageURLStr:urlStr placeHolderImage:image loadingIndicate:NO];
}

-(void)setImageURL:(NSURL *)url placeHolderImage:(UIImage *)image loadingIndicate:(BOOL)indicate
{
    [self setDisplayImage:image];
    
    if(!url)
        return;
    
    NSURLSession *session = [[self class] loadSession];
    
    __weak UIActivityIndicatorView *indicatorV = nil;
    if(indicate)
    {
        indicatorV = [self indicatorView];
        [indicatorV startAnimating];
    }
    
    __weak typeof(self) wSelf = self;
    NSURLSessionDataTask *dtsk = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if([response.URL.absoluteString isEqualToString:url.absoluteString])
        {
            UIImage *image;
            if(!error)
            {
                image = [UIImage imageWithData:data];
                
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [wSelf setDisplayImage:image];
                [indicatorV stopAnimating];
            });
            
        }
    }];
    [dtsk resume];
}
-(void)setImageURL:(NSURL *)url placeHolderImage:(UIImage *)image
{
    [self setImageURL:url placeHolderImage:image loadingIndicate:NO];
}

-(void)setDisplayImage:(UIImage *)image
{
    
    if([self respondsToSelector:@selector(setImage:)])
    {
        [self performSelector:@selector(setImage:) withObject:image];
    }
    else if([self isKindOfClass:[UIButton class]])
    {
        UIButton *b = (UIButton *)self;
        [b setImage:image forState:UIControlStateNormal];
    }
    else if([self respondsToSelector:@selector(setBackgroundImage:)])
    {
        [self performSelector:@selector(setBackgroundImage:) withObject:image];
    }
    else
    {
        self.layer.contents = (__bridge id _Nullable)(image.CGImage);
    }
}

@end
